package com.century.sjt.activity.Topic;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.R;
import com.century.sjt.activity.BaseActivity;
import com.century.sjt.fragment.MineTabSquareFragment;
import com.century.sjt.fragment.SocialTabSquareFragment;
import com.century.sjt.logic.ImgFileListActivity;
import com.century.sjt.util.CompressUtil;
import com.century.sjt.util.Constant;
import com.century.sjt.util.UploadApi;
import com.century.sjt.util.volleyUtil.ResponseListener;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import android.support.v7.app.ActionBarActivity;
//import android.text.method.Touch;
//import android.view.Menu;
//import android.view.MenuItem;
//import android.widget.ListView;
//import com.android.volley.toolbox.NetworkImageView;


public class MyPublishTopicActivity extends BaseActivity {
    //private SjtTitleBar titleBar;
//    private ImageButton btnSys;                                     //返回按钮
//    private TextView mTitle;                                        //程序标题
//    private LinearLayout leftLinLayout;                             //左边的线性布局
//    private ImageButton btnInfomation;                          //上方右边按钮
    //private NetworkImageView networkImageView1;
    private ImageView imageView1;
    private ImageView imageView2;
    private ImageView imageView3;
    private ImageView imageView4;
    private ImageView imageView5;
    private ImageView imageView6;
    private ImageView imageView7;
    private ImageView imageView8;
    private ImageView imageView9;

    private LinearLayout mLinearLayoutRow1;
    private LinearLayout mLinearLayoutRow2;
    private LinearLayout mLinearLayoutRow3;
    private LinearLayout left_layout;
    private LinearLayout right_layout;

    private TextView title;
    private TextView right_icon;
    private TextView left_icon;

    private String content;
    private String content1;
    private EditText mEditText;

    private List<ImageView> mViews = new ArrayList<>();

    //ListView listView;
    ArrayList<String> listfile = new ArrayList<String>();
    private List<String> imageIdArr = new ArrayList<>();

    private static RequestQueue mQueue;
    private ProgressDialog progressDialog;

    private LinearLayout layoutInput;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_publish_topic);

        Intent intent = this.getIntent();
        content = intent.getStringExtra("content");

        //titleBar = (SjtTitleBar) findViewById(R.id.title_bar);
        //       标题栏
        //titleBar.setRightIconResourc(getResources().getString(R.string.text_publish));
        //titleBar.setRightIconSize();
//        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                finish();
//            }
//        });
//        titleBar.setRightLayoutClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                progressDialog = ProgressDialog.show(MyPublishTopicActivity.this,getResources().getString(R.string.error_write_topic),getResources().getString(R.string.error_write_send_waitting),false,false);
//                progressDialog.setCancelable(true);
//                content = mEditText.getText().toString();
//                if (content.trim().equals("")) {
//                    if(progressDialog!=null)progressDialog.dismiss();
//                    Toast.makeText(MyPublishTopicActivity.this, getResources().getString(R.string.error_write_topic_isnull), Toast.LENGTH_LONG).show();
//                } else {
//                    if(listfile.size()==0) {
//                        sendTopicContent();
//                    }
//                    else {
//                        sendTopicAll();
//                    }
//                }
//            }
//        });
        //titleBar.setTitle(getResources().getString(R.string.tab_write_topic));
        left_layout= (LinearLayout) findViewById(R.id.left_layout);
        title= (TextView) findViewById(R.id.title);
        right_layout= (LinearLayout) findViewById(R.id.right_layout);
        right_icon= (TextView) findViewById(R.id.right_icon);
        left_icon= (TextView) findViewById(R.id.left_icon);
        Typeface iconfont = Typeface.createFromAsset(getAssets(), "iconfont.ttf");

        title.setText(getResources().getString(R.string.tab_write_topic));
        right_icon.setText(getResources().getString(R.string.text_publish));
        left_icon.setTypeface(iconfont);

        mQueue = Volley.newRequestQueue(this);

        mEditText = (EditText) findViewById(R.id.et_publish_content);
        mEditText.setText(content);

        //networkImageView1 = (NetworkImageView) findViewById(R.id.iv_publish_to_pic1);
        imageView1 = (ImageView) findViewById(R.id.iv_publish_to_pic1);
        imageView2 = (ImageView) findViewById(R.id.iv_publish_to_pic2);
        imageView3 = (ImageView) findViewById(R.id.iv_publish_to_pic3);
        imageView4 = (ImageView) findViewById(R.id.iv_publish_to_pic4);
        imageView5 = (ImageView) findViewById(R.id.iv_publish_to_pic5);
        imageView6 = (ImageView) findViewById(R.id.iv_publish_to_pic6);
        imageView7 = (ImageView) findViewById(R.id.iv_publish_to_pic7);
        imageView8 = (ImageView) findViewById(R.id.iv_publish_to_pic8);
        imageView9 = (ImageView) findViewById(R.id.iv_publish_to_pic9);

        mLinearLayoutRow1 = (LinearLayout) findViewById(R.id.ll_publish_to_pic_row1);
        mLinearLayoutRow2 = (LinearLayout) findViewById(R.id.ll_publish_to_pic_row2);
        mLinearLayoutRow3 = (LinearLayout) findViewById(R.id.ll_publish_to_pic_row3);

//        layoutInput = (LinearLayout) findViewById(R.id.layout_publish_content);
//        layoutInput.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mEditText.setSelected(true);
//            }
//        });
        mViews.add(imageView1);
        mViews.add(imageView2);
        mViews.add(imageView3);
        mViews.add(imageView4);
        mViews.add(imageView5);
        mViews.add(imageView6);
        mViews.add(imageView7);
        mViews.add(imageView8);
        mViews.add(imageView9);
        ViewGone();

        //listView=(ListView) findViewById(R.id.my_publish_pic_listView1);
        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {
            if (bundle.getStringArrayList("files") != null) {
                listfile = bundle.getStringArrayList("files");
                //listView.setVisibility(View.VISIBLE);
                ArrayAdapter<String> arryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listfile);
                if (listfile.size() != 0) {
                    mLinearLayoutRow1.setVisibility(View.VISIBLE);
                    for (int i = 0; i < listfile.size(); i++) {
//                        if (listfile.size() > 3) {
//                            mLinearLayoutRow2.setVisibility(View.VISIBLE);
//                        }
//                        if (listfile.size() > 6) {
//                            mLinearLayoutRow3.setVisibility(View.VISIBLE);
//                        }
                        ViewSet(i+1);
                        mViews.get(i).setVisibility(View.VISIBLE);
                        String strSrc = listfile.get(i);
                        Bitmap bitmap = compressUserHeadImg(strSrc);
                        mViews.get(i).setImageBitmap(bitmap);
                        mViews.get(i).setEnabled(false);

                        //Toast.makeText(MyPublishTopicActivity.this, strSrc, Toast.LENGTH_SHORT).show();
                    }
                } else {
//                    mLinearLayoutRow1.setVisibility(View.GONE);
                }
                //listView.setAdapter(arryAdapter);
            }
        }
        initEvent();
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initEvent() {
        left_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        right_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    progressDialog = ProgressDialog.show(MyPublishTopicActivity.this,getResources().getString(R.string.error_write_topic),getResources().getString(R.string.error_write_send_waitting),false,false);
                    progressDialog.setCancelable(true);
                    content = mEditText.getText().toString();
                    if (content.trim().equals("")) {
                        if(progressDialog!=null)progressDialog.dismiss();
                        Toast.makeText(MyPublishTopicActivity.this, getResources().getString(R.string.error_write_topic_isnull), Toast.LENGTH_LONG).show();
                    } else {
                        if(listfile.size()==0) {
                            sendTopicContent();
                        }
                        else {
                            sendTopicAll();
                        }
                    }
                }
        });

    }

    @Override
    protected void initData() {

    }

    private void sendTopicAll() {
        progressDialog = ProgressDialog.show(MyPublishTopicActivity.this, getResources().getString(R.string.error_upload_picture),getResources().getString(R.string.error_upload_picture_send_waitting) , false, false);
        for (int i = 0; i < listfile.size(); i++) {
            if (!listfile.get(i).equals("")) {
                Bitmap bitmap = CompressUtil.compressImg(listfile.get(i));
                UploadApi.uploadImg(bitmap, new ResponseListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
//                        progressDialog.dismiss();
                        Log.e("sjt", "上传图片错误：" + error.getLocalizedMessage());
                    }

                    @Override
                    public void onResponse(Object response) {
                        Log.e("sjt", "获取图片id1" + response.toString());
                        try {
//                            progressDialog.dismiss();
                            JSONTokener jsonParser = new JSONTokener((String) response);
                            JSONObject res = (JSONObject) jsonParser.nextValue();
                            String code = res.getString("code");
                            if (code.equals("200")) {
                                JSONObject data = res.getJSONObject("data");
                                String sysId = data.getString("sysId");
                                Log.e("sjt", "获得图片id:" + sysId);
                                imageIdArr.add(sysId);
                                if (imageIdArr.size() == listfile.size()) {
                                    sendTopicContent();
                                }
                            } else {
                                String message = res.getString("message");
                                Toast.makeText(MyPublishTopicActivity.this, getResources().getString(R.string.error_upload_wrong) + message, Toast.LENGTH_LONG).show();
                            }
                        } catch (Exception e) {
//                            progressDialog.dismiss();
                            e.printStackTrace();
                            Toast.makeText(MyPublishTopicActivity.this, getResources().getString(R.string.error_service), Toast.LENGTH_LONG).show();
                        }
                    }
                }, mQueue);
            }
        }
    }

    private void sendTopicContent() {
        //开始发布话题
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.PublishTopicHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if(progressDialog!=null)progressDialog.dismiss();
//                    Log.e("publish上传", response);t
                    JSONTokener jsonParser = new JSONTokener((String) response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {
//                        Log.e("publish上传", message);
                        Toast.makeText(MyPublishTopicActivity.this, getResources().getString(R.string.error_publish_success), Toast.LENGTH_LONG).show();
                        Message message1 = new Message();
                        message1.what=2;
                        MineTabSquareFragment.mHandler.sendMessage(message1);

                        Message message2 = new Message();
                        message2.what=2;
                        SocialTabSquareFragment.mHandler.sendMessage(message2);

                        finish();
                    } else {
//                        Log.e("publish上传", message);
                        Toast.makeText(MyPublishTopicActivity.this, message, Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(MyPublishTopicActivity.this, getResources().getString(R.string.error_service), Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                if(progressDialog!=null)progressDialog.dismiss();
                Toast.makeText(MyPublishTopicActivity.this, getResources().getString(R.string.error_network), Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
//                                                        final String userid = SjtMainActivity.mainSharePreferences.getString("userid", "");
                String userId = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE).getString("userId", "");
                Map<String, String> map = new HashMap<>();
                map.put("content", content);
                String themePic = "";
                for (int i = 0; i < imageIdArr.size(); i++) {
                    if (i>0){
                        String imge = "|"+imageIdArr.get(i);
                        Log.e("imge",imge);
                        themePic +=imge;
                    }else {
                        themePic=imageIdArr.get(i);
                    }

                }
                Log.e("imge",themePic);
                map.put("themePic", themePic);

                map.put("loginId", userId);
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String cookie = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE).getString("cookie", "");
                String rememberMeValue = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE).getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
//                Log.e("cookie", cookieValue);
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
        //结束发布话题
    }

    private void ViewGone() {

        for (int i = 0; i < 9; i++) {
            mViews.get(i).setVisibility(View.GONE);
        }

        mLinearLayoutRow1.setVisibility(View.GONE);
        mLinearLayoutRow2.setVisibility(View.GONE);
        mLinearLayoutRow3.setVisibility(View.GONE);
        ViewSet(0);
    }
    private void ViewSet(int i){
        if (i<9){
            mLinearLayoutRow1.setVisibility(View.VISIBLE);
            mViews.get(i).setVisibility(View.VISIBLE);
            mViews.get(i).setImageDrawable(getResources().getDrawable(R.mipmap.shape_18));
            mViews.get(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(MyPublishTopicActivity.this, ImgFileListActivity.class);
                    content = mEditText.getText().toString();
                    intent.putExtra("content",content);
                    startActivity(intent);
                }
            });
        }
        if (i>2){
            mLinearLayoutRow2.setVisibility(View.VISIBLE);
        }
        if (i>5){
            mLinearLayoutRow3.setVisibility(View.VISIBLE);
        }
    }




    private Bitmap compressUserHeadImg(String pathName){
        Bitmap bitmap=null;
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(pathName, options);
        // 源图片的宽度
        //int width = options.outWidth;
//        options.inSampleSize = calculateInSampleSize(options, 1600);            //限定为1600像素
        options.inSampleSize = computeSampleSize(options,-1,1600*900);
        options.inJustDecodeBounds = false;
        try{
            bitmap=BitmapFactory.decodeFile(pathName, options);
        }catch (Exception e){

        }
        return bitmap;
    }

    public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }
        return roundedSize;
    }

    private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;
        int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));
        if (upperBound < lowerBound) {
            // return the larger one when there is no overlapping zone.
            return lowerBound;
        }
        if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }


}
